package fun.tan90.easy.binlog.plugin.mqtt.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.mqtt.listener.MqttEventProcessor;
import fun.tan90.easy.binlog.plugin.mqtt.service.impl.MqttPluginService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class MqttPluginAutoConfiguration {

    public MqttPluginAutoConfiguration() {
        log.info("init MqttPlugin");
    }

    @Bean
    public MqttClientCacheLoader mqttClientCacheLoader() {
        return new MqttClientCacheLoader();
    }

    @Bean
    public LoadingCache<String, MqttClient> mqttClientCache(MqttClientCacheLoader mqttClientCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.MQTT.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(mqttClientCacheLoader);
    }

    @Bean
    public MqttEventProcessor mqttEventProcessor(LoadingCache<String, MqttClient> mqttClientCache) {
        return new MqttEventProcessor(mqttClientCache);
    }

    @Bean(name = "mqtt")
    public PluginService mqttPluginService() {
        return new MqttPluginService();
    }

}
